/**
 * 登录页面组件
 * Created by yuzhou on 16/9/24.
 */

define([
    'vue','debug', 'text!tpl/login.html',
    'vuex/actions/user', 'api/user',
    'icheck'
], function(Vue, Debug, mainHtml, userAction, userApi) {

    var debug = Debug('App:Login')

    return Vue.extend({
        template: mainHtml,
        data: function() {
            return {
                fromUrl: null,
                result: null,
                username: '',
                password: '',
                remember: true
            }
        },
        components: {

        },
        route: {
            activate: function(transition){
                this.$dispatch('body-class', 'hold-transition login-page')
                this.fromUrl = transition.from.path
                transition.next()
            }
        },
        vuex: {
            actions: {
                setLoginUser: userAction.setLoginUser
            }
        },
        methods: {
            resetResult: function() {
                this.result = null
            },
            submit: function() {
                var me = this
                var data = {
                    username: this.username,
                    password: this.password,
                    remember: this.remember
                }

                userApi.login(data, function(user){
                    me.setLoginUser(user)
                    me.$router.go(me.fromUrl? me.fromUrl : '/')
                }, function(error){
                     me.result = {
                         'ok': false,
                         'error': error
                     }
                })

            }
        },
        ready: function(){
            debug('Login component is ready')
            var me = this
            $(this.$el).find('input').iCheck({
                checkboxClass: 'icheckbox_square-blue',
                radioClass: 'iradio_square-blue',
                increaseArea: '20%' // optional
            }).on('ifChecked', function(event){
                me.remember = true
            }).on('ifUnchecked', function(event){
                me.remember = false
            })
        }
    })
})